<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="username"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.trim="userage"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
          
        </tr>
        <tr v-for="(item, i) in arr" :key="i">
          <td>{{ i + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(i)">删除</button>
            <button @click="edit(i)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      username:'',
      userage:0,
      arr: [
        { name: "吴逸凡", age: 18, sex: "男" },
        { name: "吴志宇", age: 17, sex: '男' },
      ],
      gender:'',
      //保存编辑对象的索引
      editnewarr:null
    };
  },

  methods: {
    add(){
      //添加
      let newArr ={
        name:this.username,
        age:this.userage,
        sex:this.gender
      }
      //修改
      //当索引不为null时
      if(this.editnewarr!==null){
        //更新该属性的值
        this.$set(this.arr,this.editnewarr,newArr)
        //更新索引为null
        this.editnewarr =null
        //更新input状态
        this.gender=''
        this.userage =''
        this.username=''
      }else{
        //添加
        this.arr.push(newArr)
      }
    },
    del(i){
      //删除点击的一列数据
      this.arr.splice(i,1)
    },
    edit(i){
      //获取要编辑的对象信息
      const editarr =this.arr[i]
      this.username =editarr.name
      this.userage =editarr.age
      this.gender =editarr.sex
      //保存索引值
      this.editnewarr =i
    }
  },
  computed: {},
};
</script>

<style scoped></style>
